<template>
  <div>
    <el-dialog width="500px" title="修改密码" :visible="dialogVisible" :before-close="handleClose">
      <el-form ref="formData" :model="formData" :rules="rules">
        <el-form-item prop="oldPassword" label="原密码" :label-width="formLabelWidth">
          <el-input v-model.trim="formData.oldPassword" placeholder="请输入原密码" />
        </el-form-item>
        <el-form-item prop="newPassword" label="新密码" :label-width="formLabelWidth">
          <el-input v-model.trim="formData.newPassword" placeholder="请输入新密码" />
        </el-form-item>
        <el-form-item prop="confirmPassword" label="重复密码" :label-width="formLabelWidth">
          <el-input v-model.trim="formData.confirmPassword" placeholder="请重复新密码" />
        </el-form-item>
        <el-form-item class="dialog-footer">
          <el-button type="primary" @click="confirmFn">确定修改</el-button>
          <el-button @click="handleClose">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { Message } from 'element-ui'

export default {
  props: ['dialogVisible'],
  data() {
    return {
      formLabelWidth: '80px',
      formData: {
        // 原密码
        oldPassword: '',
        // 新密码
        newPassword: '',
        // 确认密码
        confirmPassword: ''
      },
      rules: {
        oldPassword: [
          { required: true, message: '请输入原密码', trigger: 'blur' },
          { pattern: /^[a-zA-Z0-9@%]{6,12}/, message: '请输入6-12位字符，不能包含空格', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入原密码', trigger: 'blur' },
          { pattern: /^[a-zA-Z0-9@%]{6,12}/, message: '请输入6-12位字符，不能包含空格', trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请输入原密码', trigger: 'blur' },
          { pattern: /^[a-zA-Z0-9@%]{6,12}/, message: '请输入6-12位字符，不能包含空格', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value !== this.formData.newPassword) {
                callback(new Error('两次输入的密码不一致'))
              } else {
                callback()
              }
            },
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    // 确定修改
    async confirmFn() {
      // 表单的整体校验
      await this.$refs.formData.validate((validate) => {
        if (validate) {
          // 调用接口发送请求
          // 提示框
          Message.success('修改成功')
          this.handleClose()
        }
      })
    },
    // 关闭弹窗
    handleClose() {
      // 重置表单
      this.$refs.formData.resetFields()
      // 通知父组件关闭弹窗
      this.$emit('update:dialogVisible', false)
    }
  }
}
</script>

<style lang="scss" scoped></style>
